package main

import (
	"golang.org/x/crypto/ssh"
	"log"
	"net"
)

//创建SSH客户端
func createSshClient(serverAddr, username, password string) *ssh.Client {
	config := &ssh.ClientConfig{
		User: username,
		Auth: []ssh.AuthMethod{
			ssh.Password(password),
		},
	}
	sshClient, err := ssh.Dial("tcp", serverAddr, config)
	if err != nil {
		log.Fatal("无法连接SSH服务器: " + err.Error())
	}

	return sshClient
}

//转发指定服务器请求到指定端口
func createTunnel(sshClient *ssh.Client, listenAddress, connectAddress string) {
	sshListener, err := sshClient.Listen("tcp", listenAddress)
	if err != nil {
		log.Fatal("监听" + listenAddress + "失败: " + err.Error())
	}
	defer sshListener.Close()

	for {
		sshConn, err := sshListener.Accept()
		if err != nil {
			log.Println(listenAddress+"收到异常请求: ", err)
			continue
		}

		//连接本地端口
		localConn, err := net.Dial("tcp", connectAddress)
		if err != nil {
			sshConn.Close()
			log.Println("SSH客户端通道建立失败: ", err)
			continue
		}

		log.Println("SSH新隧道: ", sshConn.RemoteAddr(), " <-> ", connectAddress)

		//读写隧道数据直至断开
		disconnect := make(chan bool)
		go forwardRequest(sshConn, localConn, disconnect)
		go forwardRequest(localConn, sshConn, disconnect)

		<-disconnect
	}
}
